<template>
  <div class="about" id="about" ref="about">
    <div class="prev" @click="back"><img src="../assets/img/About/back.png"></img></div>
    <div class="screen" @click="screenFunc"><img :src="noSleepS?require('../assets/img/About/yellow.png'):require('../assets/img/About/black.png')" alt=""></div>
    <div v-if="$store.state.list.length>0">
      <div class="title">{{$store.state.list[$store.state.musicIndex].title}}</div>
      <div class="author">{{$store.state.list[$store.state.musicIndex].author}}</div>
      <geci :lyric="$store.state.list[$store.state.musicIndex].lyric"></geci>
    </div>
     <div class="pos_bot">
        <div class="progress">
          <span class="start_time">{{$store.state.startTime}}</span>
          <van-progress :percentage="$store.state.move" color="#2b9939"  class="jindu" pivot-text=' ' stroke-width="2"/>
          <span class="end_time">{{$store.state.endTime}}</span>
        </div>
        <div class="btnGroup">
          <img class="aixin" :src="$store.state.aixin?require('../assets/img/About/aixin_active.png'):require('../assets/img/About/aixin.png')" @click="Collection"/>
          <img src="../assets/img/About/ljiantou.png" @click="prevClick"/>
          <img :src="$store.state.play?require('../assets/img/About/over.png'):require('../assets/img/About/open.png')" @click="changeClick"/>
          <img src="../assets/img/About/rjiantou.png" @click="nextClick"/>
          <img :src="$store.state.xunhuan?require('../assets/img/About/list.png'):require('../assets/img/About/1.png')" @click="xunHuanFun"/>
        </div>
     </div>
  </div>
</template>
<script>
import geci from '../components/geci/geci.vue';
import { get, post } from '../../utils/request.js';
// 请求封装
export default {
  name: 'About',
  components: {
    geci,
  },
  data() {
    return {
      btnState: true, // 播放按钮的状态,
      noxiping: new this.$NoSleep(),
      noSleepS: false,
    };
  },
  methods: {
    xunHuanFun() {
      const store = this.$store.state;
      store.xunhuan = !store.xunhuan;
      if (store.xunhuan) {
        this.$toast({
          message: '当前列表循环',
          position: 'top',
        });
      } else {
        this.$toast({
          message: '当前单曲循环',
          position: 'top',
        });
      }
    },
    // 判断小红心的true和false
    hongxin() {
      const store = this.$store.state;
      store.aixin = false;
      if (localStorage.getItem('list4') == null) {
        localStorage.setItem('list4', '[]');
      } else {
        const arr3 = JSON.parse(localStorage.getItem('list4'));
        const hash = this.$store.state.bof;
        for (let i = 0; i < arr3.length; i++) {
          if (arr3[i].hash == hash) {
            store.aixin = true; break;
          }
        }
      }
    },
    // 防止熄屏
    screenFunc(e){
      if(this.noSleepS == true){
        this.noxiping.disable();
        this.$toast('关闭屏幕常亮');
        this.noSleepS = false
      }else{
        this.noxiping.enable();
        this.$toast('打开屏幕常亮');
        this.noSleepS = true
      }

    },
    // 收藏功能
    Collection() {
      const arr = JSON.parse(localStorage.getItem('list4'));
      const store = this.$store.state;
      store.aixin = !store.aixin;
      if (store.aixin) {
        const demo = {};
        demo.hash = this.$route.query.hash;
        demo.filename = `${store.list[store.musicIndex].title} - ${store.list[store.musicIndex].author}`;
        demo.duration = store.list[store.musicIndex].duration;
        demo.album_id = this.$route.query.album_id;
        arr.push(demo);
        localStorage.setItem('list4', JSON.stringify(arr));
        this.$toast.success('成功收藏');
      } else {
        const { hash } = this.$route.query;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].hash == hash) {
            arr.splice(i, 1);
            localStorage.setItem('list4', JSON.stringify(arr));
          }
        }
        this.$toast.success('取消收藏');
      }
    },
    	back() {
      this.$router.back();
    	},
    	changeClick() {
      const audio = document.querySelector('audio');
    		this.btnState = !this.btnState;
      if (this.btnState) {
        this.$store.state.play = true;
        audio.play();
      } else {
        this.$store.state.play = false;
        audio.pause();
      }
      console.log(this.$store.state.play);
    	},
    // 上一首
    	prevClick() {
      const store = this.$store.state;
      if (store.list.length > 0) {
        if (store.musicIndex != 0) {
          	store.musicIndex--;// 歌曲list的索引
        } else if (store.musicIndex == 0) {
          store.musicIndex = store.list.length - 1;
        }
        store.m = 0;// 歌词盒子的transform:translateY(-m)的值
        store.action = 0;// 根据播放进度，动态改变的歌词li的索引值
        this.load();// 重载歌曲src并播放
        this.time_list();
        this.getImg();// 获取背景图
      }

      if (store.list[store.musicIndex].src == '') {
        this.prevClick();
      }
      this.gundong();
      this.$store.state.bof = store.list[store.musicIndex].hash;// 标识当前播放
      this.hongxin();
    	},
    	nextClick() {
      const store = this.$store.state;
      if (store.list.length > 0) {
        if (store.musicIndex < store.list.length - 1) {
          store.musicIndex++;
          store.m = 0;// 下一首初始化歌词盒子的translateY移动
          store.action = 0;// 初始化索引
          this.time_list();
        } else if (store.musicIndex == store.list.length - 1) {
          store.musicIndex = 0;
          store.m = 0;// 下一首初始化歌词盒子的translateY移动
          store.action = 0;// 初始化索引
          this.time_list();
        }
      }
      this.load();
      this.getImg();// 获取背景图
      if (store.list[store.musicIndex].src == '') {
        this.nextClick();
      }
      this.gundong();
      this.$store.state.bof = store.list[store.musicIndex].hash;// 标识当前播放
      if (store.musicIndex == store.list.length - 1) {
        store.play = false;
        this.btnState = false;
      }
      this.hongxin();
    	},
    // 发送每行歌词的高度，和歌词盒子给vuex
    gundong() {
      const store = this.$store.state;
      setTimeout(() => {
        if (store.list[store.musicIndex].lyric.length != 0) {
          // 获取自适应的歌词li高度
          // this.$store.state.liHeight=this.$refs.geci_li[0].offsetHeight;
          const arr = [];
          let demo = 0;
          document.querySelectorAll('.geci_li').forEach((item) => {
            demo += item.offsetHeight;
            arr.push(demo);
          });
          this.$store.state.liHeight = arr;
          // 把歌词盒子对象传到vuex处理
          this.$store.state.ge = document.querySelector('.geci_list');
        } else {
          this.$store.state.liHeight = 0;
          this.$store.state.ge = null;
        }
      }, 100);
    },
    time_list() {
      const timeList = [];// 把[00:00.0]时间转化为保留两位小数的秒数
      if (this.$store.state.list[this.$store.state.musicIndex].lyric.length != 0) {
        for (const i in this.$store.state.list[this.$store.state.musicIndex].lyric) {
          // 根据前面两位数*60得出秒数+后面的秒数
          timeList.push(parseFloat((this.$store.state.list[this.$store.state.musicIndex].lyric[i].time).substr(1, 3)) * 60 + parseFloat((this.$store.state.list[this.$store.state.musicIndex].lyric[i].time).substr(4, 9)));
        }
        this.$store.state.timeList = timeList;
      }
    },
    load() {
      const audio = document.querySelector('audio');
      audio.load();
      audio.oncanplay = () => { // 歌缓存到可以播放的时候
        audio.play();
        this.btnState = true;
        this.$store.state.play = true;
        const duration = this.tos(audio.duration);
        this.$store.commit('duration', duration);
      };
    },
    tos(endTime) {
      	// 将秒转化为时分秒
      	  let secondTime = parseInt(endTime);// 将传入的秒的值转化为Number
      	  let min = 0;// 初始化分
      	  let h = 0;// 初始化小时
      	  let result = '';
      	  if (secondTime > 60) { // 如果秒数大于60，将秒数转换成整数
      		min = parseInt(secondTime / 60);// 获取分钟，除以60取整数，得到整数分钟
      		secondTime = parseInt(secondTime % 60);// 获取秒数，秒数取佘，得到整数秒数
      		if (min > 60) { // 如果分钟大于60，将分钟转换成小时
      		  h = parseInt(min / 60);// 获取小时，获取分钟除以60，得到整数小时
      		  min = parseInt(min % 60); // 获取小时后取佘的分，获取分钟除以60取佘的分
      		}
      	  }
      	  if (h == 0) {
      		  result = `${min.toString().padStart(2, '0')}:${secondTime.toString().padStart(2, '0')}`;
      	  } else {
      		  result = `${h.toString().padStart(2, '0')}:${min.toString().padStart(2, '0')}:${secondTime.toString().padStart(2, '0')}`;
      	  }
      	  return result;
    },
    progress() {
      const audio = document.querySelector('audio');

      // 屏幕宽带
      const screenWidth = window.screen.width;
      // 左边开始时间的宽度
      const startTimeWidth = screenWidth * 1 / 6;
      // 进度条的宽度
      const jinduTotal = screenWidth * 4 / 6;
      const progress = document.querySelector('.jindu');
      progress.onclick = (e) => {
        // 移动的宽度
        const clickWidth = e.clientX - startTimeWidth;
        // 把移动宽度转化为百分比
        this.$store.state.move = clickWidth / jinduTotal * 100;
        audio.currentTime = clickWidth / jinduTotal * audio.duration;// 点击进度条计算出播放时长
      };

      const ball = document.querySelector('.van-progress__pivot');// 进度条的小球
      ball.ontouchmove = (e) => {
        // 移动的宽度
        const touchWidth = e.touches[0].clientX - startTimeWidth;
        // 判断触摸移动是否超出进度条的长度
        if (touchWidth > screenWidth * 4 / 6 || touchWidth < 0) {
          return;
        }
        this.$store.state.move = touchWidth / jinduTotal * 100;
        audio.currentTime = touchWidth / jinduTotal * audio.duration;
      };
    },
    getImg() {
      const store = this.$store.state;
      if (store.list[store.musicIndex].img.indexOf('http') > -1) {
        document.styleSheets[0].addRule('.about::before', `background: transparent url(${store.list[store.musicIndex].img})center center no-repeat !important`);
        document.styleSheets[0].insertRule(`.about::before { background: transparent url(${store.list[store.musicIndex].img})center center no-repeat !important }`, 0);
      }
    },

  },
  created() {
    this.aboutShow = true;
    const store = this.$store.state;
    const { hash } = this.$route.query;// vue路由传过来的参数
    const { album_id } = this.$route.query;
    if (hash != '') {
      for (let i = 0; i < store.list.length; i++) {
        if (store.list[i].hash == hash) {
          if (store.list[store.musicIndex].hash != hash) {
            this.load();
          }
          store.musicIndex = i;
          this.getImg();
          return;
        }
      }
      // 发起post请求
      post(`https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash=${hash}&album_id=${album_id}&dfid=1ZxK2M2ZbSkB0wBOnV173l7y&mid=ac9eb74c90f1f717b99aaab44a337f67&platid=4&_=1600657413199`, {}).then((res) => {
        const arr = {};
        const { data } = res.data;
        if (data.play_url == '') {
          this.$toast.fail('播放失败');// vant组件提示失败
          this.back();
          return;
        }
        if (data.is_free_part == 1) {
          this.$toast.fail('试听歌曲');// vant组件提示失败
        }
        arr.hash = data.hash;
        arr.title = data.audio_name.split(' - ')[1];
        arr.author = data.audio_name.split(' - ')[0];
        arr.src = data.play_url;
        arr.img = data.img;
        arr.lyric = [];
        data.lyrics.split(/\n/).forEach((item) => {
          if (item.split(']')[1] != '\r' && item.split(']')[1] != undefined) {
            const obj = { time: `${item.split(']')[0]}]`, name: item.split(']')[1] };
            arr.lyric.push(obj);
          }
        });

        store.list.splice(store.musicIndex + 1, 0, arr);// 添加下一首歌的信息
        this.nextClick();
        // document.styleSheets[0].insertRule(".about::before{background: transparent url("++")center center no-repeat}", 0);
      });
    } else {
      store.musicIndex = -1;
      this.nextClick();
    }
  },
  mounted() {
    // 进度条事件
    this.progress();
    // this.$refs.about.style.height=document.documentElement.clientHeight +'px';
    const store = this.$store.state;
    store.play = !document.querySelector('audio').paused;
    this.btnState = !!store.play;
    // 收藏块的小红心状态
    this.hongxin();
  },
  beforeRouteLeave(to, from, next) {
    if (this.noSleepS == true) {
      this.noxiping.disable();
      this.noSleepS == false;
    }
    next();
  },
};
</script>
<style lang="scss" scoped>
  .about{
  	margin: 0 auto;
  	text-align: center;
    height: 100vh;
  	color: #fff;
    background-color: rgba(0,0,0,0.3);
    position: relative;
  }
  .about::before{
  	content:'';
  	position:absolute;
  	top: 0;
  	left:0;
  	width:100%;
  	height:100%;
    background: transparent url(../assets/img/About/kegou.jpg)center center no-repeat;
  	filter:blur(10px);
  	z-index:-1;
  	background-size:cover;
  }
  .title,.author{
  	text-align: center;
  }
  .title{
  	font-weight: bold;
  	font-size: 50px;
  	padding-top: 15%;
  	padding-bottom: 25px;
    width: 85%;
    margin: 0 auto;
  }
  .author{
  	font-size: 40px;
  }

  .progress{
  	display: flex;
  	justify-content: space-around;
  	position: relative;
  	.start_time,.end_time{
  		// width: 5%;
  		font-size: 28px;
  		flex: 1;
  	}
    .jindu{
      flex: 4;
      margin-top: 12px;
    }

  }
  .btnGroup {
  	// width: 400px;
  	margin: 30px auto 0;
  	text-align: center;
  	height: 80px;
    // position: relative;
  }

  .btnGroup img {
  	margin: 20px;
  	width: 48px;
  	height: 48px;
  	vertical-align: middle;
  }

  .btnGroup img:nth-child(3) {
  	width: 65px;
  	height: 65px;
  }

  movable-area{
  	position: absolute;
  	left: 50%;
  	top: 17%;
  	width: 75%;
  	height: 28px;
  	transform: translateX(-50%);
  	movable-div{
  		width: 5%;
  		height: 100%;
  		background-color: #fff;
  		border-radius: 50%;
  	}
  }

  .prev{
  	position: fixed;
  	top: 5%;
  	left: 20px;
  	img{
  		width: 45px;
  		height: 45px;
  	}
  }
  .pos_bot{
    position: absolute;
    bottom: 8%;
    left: 0;
    width: 100%;
  }
  .screen{
    position: fixed;
    top: 5%;
    right: 20px;
    img{
      width: 52px;
      height: 52px;
    }
  }
</style>
<style>
  .van-progress__pivot{
    display: block;
    min-width: 22px !important;
    min-height: 22px !important;
    border-radius: 50%;
  }

</style>
